<?php

/**
 * 缓存加数据库的双重存储方案
 *
 * 暂时不考虑数据的
 *
 * @author ananda
 */
class Pattern_DoubleStorage extends Pattern
{
    protected $_prefix = 'dsd_';
    protected $_category;

    protected $_cache_adapter;
    protected $_db_adapter;

    protected $_fields = array();
    protected $_rules  = array();

    protected $_fields_extra = array(
        'primary' => 'id',
        'insert_ignore' => null,
    );

    protected $_primary_handler  = null;
    protected $_generate_handler = null;

    public function __construct() {
        if ($this->_primary_handler) {
            $this->_primary_handler = new $this->_primary_handler($this->_category, $this);
        }

        $this->init();
    }

    protected function init();

    protected function generateKey($id)
    {
        if ($this->_generate_handler) {
            // do something
        } else {
            $key = $this->_prefix.$this->_category.'_';
        }
        return $key;
    }

    public function create($record)
    {
        // 这里还缺验证

        // 如果有主键句柄，则先取出主键
        if ($this->_primary_handler) {
            $insert_id = $this->_primary_handler->getInsertId();
        }

        // 字段处理
        $fields = $this->_fields;
        if ($this->_fields_extra['insert_ignore']) {
            foreach ($this->_fields_extra['insert_ignore'] as $field) {
                unset($fields[$field]);
            }
        }
        unset($this->_fields_extra['primary']);

        // 写数据库
        $sql_field = $this->_fields_extra['primary'].', '.implode(', ', $fields);
        $sql_data  = $insert_id.', "'.implode('", "', $record).'"';
        $sql_full  = "INSERT INTO $this->_category ($fieldstr) VALUES ($data_str)";
        $result    = $this->_db_adapter->exec($sql_full);
        if (!$result) {
            return false;
        }

        // 写缓存
        return $this->_cache_adapter->add($this->generateKey($insert_id), $record);
    }

    public function read()
    {

    }

    public function update()
    {

    }

    public function delete()
    {
        // 强烈不推荐删除数据
    }
}
